package com.thingcom.delinrobot.main.device;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.android.tu.loadingdialog.LoadingDailog;
import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.contrarywind.view.WheelView;
import com.gizwits.gizwifisdk.api.GizWifiDevice;
import com.gizwits.gizwifisdk.enumration.GizWifiDeviceNetStatus;
import com.gizwits.gizwifisdk.enumration.GizWifiErrorCode;
import com.thingcom.delinrobot.Common.Frame.FrameUtils;
import com.thingcom.delinrobot.Common.Frame.GetWorkingTime;
import com.thingcom.delinrobot.Common.Frame.SetWorkingTime;
import com.thingcom.delinrobot.Common.pjo.FrameType;
import com.thingcom.delinrobot.Common.pjo.WorkingTimeItem;
import com.thingcom.delinrobot.Data.GizManger;
import com.thingcom.delinrobot.R;
import com.thingcom.delinrobot.base.BaseBackFragment;
import com.thingcom.delinrobot.utils.HexStrUtils;
import com.thingcom.delinrobot.utils.HexUtil;
import com.thingcom.delinrobot.utils.MyLog;
import com.thingcom.delinrobot.view.SimpleToolbar;
import com.thingcom.delinrobot.view.SwitchButton;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.thingcom.delinrobot.utils.AppUtils.hideSoftKeyboard;

/**
 * author : YuFeng
 * e-mail : 923462992@qq.com
 * date   : 2019/11/14
 */
public class WorkingTimeBackFragment extends BaseBackFragment implements GizManger.myGizWifiDeviceListener{
    private static final String TAG = "WorkingTimeBackFragment";
    private WheelView hourWheel;
    private WheelView minuteWheel;
    private PopupWindow popupWindow;
    private View popupview;
    private int weekPosition;
    private String hour = "05";
    private String minute = "00";

    @BindView(R.id.toolbar_working_time)
    SimpleToolbar toolbarWorkingTime;
    @BindView(R.id.recycler_working_time)
    RecyclerView recyclerWorkingTime;
    @BindView(R.id.btn_set_data)
    Button btnSetData;

    private List<String> hourList;
    private List<String> minutesList;
    private WorkingTimeAdapter workingTimeAdapter;
    private List<WorkingTimeItem> workingTimeItemList;
    private LoadingDailog dialog;

    public static WorkingTimeBackFragment newInstance() {
        Bundle args = new Bundle();

        WorkingTimeBackFragment fragment = new WorkingTimeBackFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_back_working_time, container, false);
        popupview = inflater.inflate(R.layout.popup_working_time, container, false);
        unbinder = ButterKnife.bind(this, view);
   //     unbinder = ButterKnife.bind(this, popupview);
        toolbarWorkingTime.setMyLeftIcon(R.drawable.toolbar_back_two_selector);
        toolbarWorkingTime.setMinimumHeight(42);
        toolbarWorkingTime.setBackgroundColor(getResources().getColor(R.color.black_main));
        toolbarWorkingTime.setTitleStyle(getResources().getColor(R.color.white_main),13);
        toolbarWorkingTime.setLeftIconClickListener(view1 -> {
            hideSoftKeyboard(_mActivity);
            start(DeviceMainFragment.newInstance(),3);
        });
        GizManger.getInstance().setmCallback(this);
        GetWorkingTime getWorkingTime = new GetWorkingTime("00000000");
        GizManger.getInstance().GizWrite(getWorkingTime.parse());
        initView();
        return view;
    }



    @Override
    public void onResume() {
        super.onResume();

    }

    @OnClick(R.id.btn_set_data)
    public void onViewClicked() {


        byte[] dataArea = new byte[21];
        for (int i =0;i<7;i++){
            String time = workingTimeItemList.get(i).getTimeContent();
            String hour = time.substring(0,2);
            String minute = time.substring(3,5);
            dataArea[i] = Byte.parseByte(hour);
            dataArea[7+i] = Byte.parseByte(minute);
            Boolean open = workingTimeItemList.get(i).getOpen();
            if (open){
                dataArea[14+i] = 0x01;
            } else {
                dataArea[14+i] = 0x00;
            }
        }

        MyLog.i("组帧", "onViewClicked: "+HexUtil.formatHexString(dataArea));
        SetWorkingTime setWorkingTime = new SetWorkingTime("00000000",dataArea);
        GizManger.getInstance().GizWrite(setWorkingTime.parse());
        LoadingDailog.Builder loadBuilder=new LoadingDailog.Builder(getContext())
                .setCancelable(false)
                .setCancelOutside(false);
        dialog=loadBuilder.create();
        dialog.show();
        timer.start();

    }

    @Override
    public void onPause() {
        super.onPause();
        if (popupWindow!=null){
            popupWindow.dismiss();
        }
    }

    @Override
    public boolean onBackPressedSupport() {
        start(DeviceMainFragment.newInstance(),3);
        return true;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (timer!=null){
            timer.cancel();
        }
    }

    private void popup(String time){
        // 填充布局并设置弹出窗体的宽,高
        popupWindow = new PopupWindow(popupview,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        // 设置弹出窗体可点击
        popupWindow.setFocusable(true);
        // 设置弹出窗体动画效果
        popupWindow.setAnimationStyle(R.style.take_time_anim);
        // 触屏位置如果在选择框外面则销毁弹出框
        popupWindow.setOutsideTouchable(false);
        // 设置弹出窗体的背景
        popupWindow.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        popupWindow.showAtLocation(popupview,
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);

//        // 设置背景透明度
//        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
//        lp.alpha = 0.8f;
//        getActivity().getWindow().setAttributes(lp);

        // 添加窗口关闭事件
        popupWindow.setOnDismissListener(() -> {
            MyLog.i(TAG, "onDismiss: ");
//                timeView.setTextColor(getResources().getColor(R.color.black));
//                hourView.setTextColor(getResources().getColor(R.color.black));
//                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
//                lp.alpha = 1f;
//                getActivity().getWindow().setAttributes(lp);
        });
        initWheelView(time);
    }


    private void initWheelView(String time){
        String[] parts = time.split(":");
        int part1 = Integer.parseInt(parts[0]);
        int part2 = Integer.parseInt(parts[1])/15;
        hour = parts[0];
        minute = parts[1];
        hourList = new LinkedList<>();
        for (int  i = 0 ; i < 24;i++){
            String hour = i < 10? "0" + i:String.valueOf(i);
            hourList.add(hour);
        }
        minutesList = new LinkedList<>();
        for (int i = 0 ; i < 60 ;i=i+15){
            String minute = i < 10? "0" + i : String.valueOf(i);
            minutesList.add(minute);
        }
        hourWheel.setCyclic(true);
        minuteWheel.setCyclic(true);
        hourWheel.setItemsVisibleCount(5);
        minuteWheel.setItemsVisibleCount(5);
        hourWheel.setCurrentItem(part1);
        minuteWheel.setCurrentItem(part2);
        hourWheel.setTextColorCenter(Color.WHITE);
        minuteWheel.setTextColorCenter(Color.WHITE);
        hourWheel.setAdapter(new ArrayWheelAdapter<>(hourList));
        minuteWheel.setAdapter(new ArrayWheelAdapter<>(minutesList));
        hourWheel.setOnItemSelectedListener(index -> {
            hour = hourList.get(index);
//                ToastUtil.showToast(getContext(), "" + hourList.get(index));
        });
        minuteWheel.setOnItemSelectedListener(index -> {
            minute = minutesList.get(index);
//                ToastUtil.showToast(getContext(), "" + minutesList.get(index));
        });

    }

    private class WorkingTimeAdapter extends BaseQuickAdapter<WorkingTimeItem, BaseViewHolder> {

        SwitchButton switchWorkingTime;


        WorkingTimeAdapter(@Nullable List<WorkingTimeItem> data) {
            super(R.layout.working_time_item, data);
        }

        @Override
        protected void convert(BaseViewHolder helper, WorkingTimeItem item) {
            switchWorkingTime = helper.getView(R.id.switch_working_time);
            helper.setText(R.id.tv_working_time_week, item.getWeekContent());
            helper.setText(R.id.tv_working_time, item.getTimeContent());
            switchWorkingTime.setChecked(item.getOpen());
            switchWorkingTime.setOnCheckedChangeListener((view, isChecked) -> item.setOpen(isChecked));
        }
    }

    private void initView() {
        hourWheel = popupview.findViewById(R.id.hour_wheel);
        minuteWheel = popupview.findViewById(R.id.minute_wheel);
        Button popupCancel = popupview.findViewById(R.id.popup_cancel);
        Button popupConfirm = popupview.findViewById(R.id.popup_confirm);
        popupCancel.setOnClickListener(v -> popupWindow.dismiss());
        popupConfirm.setOnClickListener(v -> {
            String time = hour +":"+minute;
            workingTimeItemList.get(weekPosition).setTimeContent(time);
            workingTimeAdapter.notifyDataSetChanged();
            popupWindow.dismiss();
        });
        recyclerWorkingTime.setLayoutManager(new LinearLayoutManager(getContext(), RecyclerView.VERTICAL, false));
        workingTimeItemList = new LinkedList<>();
        workingTimeItemList.add(new WorkingTimeItem(getString(R.string.day_mon), "08:00",false));
        workingTimeItemList.add(new WorkingTimeItem(getString(R.string.day_tue), "09:00",false));
        workingTimeItemList.add(new WorkingTimeItem(getString(R.string.day_wed), "10:00",false));
        workingTimeItemList.add(new WorkingTimeItem(getString(R.string.day_thu), "08:00",false));
        workingTimeItemList.add(new WorkingTimeItem(getString(R.string.day_fri), "08:00",false));
        workingTimeItemList.add(new WorkingTimeItem(getString(R.string.day_sat), "08:00",false));
        workingTimeItemList.add(new WorkingTimeItem(getString(R.string.day_sun), "08:00",false));

        workingTimeAdapter = new WorkingTimeAdapter(workingTimeItemList);
        workingTimeAdapter.bindToRecyclerView(recyclerWorkingTime);
        workingTimeAdapter.setOnItemClickListener((adapter, view, position) -> {
            weekPosition = position;
            String time = workingTimeItemList.get(position).getTimeContent();
                popup(time);
        });

    }


    @Override
    public void didSetSubscribe(GizWifiErrorCode result, GizWifiDevice device, boolean isSubscribed) {

    }

    @Override
    public void didReceiveData(GizWifiErrorCode result, GizWifiDevice device, ConcurrentHashMap<String, Object> dataMap, int sn) {
        if (dataMap.get("binary") != null) {
//            ConcurrentHashMap<String, Object> map = (ConcurrentHashMap<String, Object>) dataMap.get("binary");
            // 扩展数据点，key为"kuozhan"
            byte[] bytes = (byte[]) dataMap.get("binary");
            String string = HexStrUtils.bytesToHexString(bytes);
            MyLog.i("收到数据", string);
            byte[] dataArea;
            FrameType identify = FrameUtils.getDataIdentifyEnum(bytes);
//            FrameUtils.sendEventByDataIdentify(identify,bytes);
            if (identify!=null){
                switch (identify) {
                    case TYPE_FRAME_ROBOT_WORK_TIME_READ:
                        dataArea = FrameUtils.getDataArea(bytes);
                        String workTime = HexStrUtils.bytesToHexString(dataArea);
                        for (int i = 0;i<7;i++){
                            int hour = Integer.valueOf(workTime.substring(2*i,2*(i+1)),16);
                            int minute = Integer.valueOf(workTime.substring(14+2*i,14+2*(i+1)),16);
                            Boolean open ;
                            open = !workTime.substring(28 + 2 * i + 1, 28 + 2 * (i + 1)).equals("0");
                            String h = hour<10?"0"+hour:String.valueOf(hour);
                            String m = minute<10?"0"+minute:String.valueOf(minute);
                            String time = h +":" + m;
                            workingTimeItemList.get(i).setTimeContent(time);
                            workingTimeItemList.get(i).setOpen(open);
                            MyLog.i("workTime", "didReceiveData: "+"hour："+hour+"minute："+minute+"open："+open);
                        }
                        workingTimeAdapter.notifyDataSetChanged();
                        break;
                    case TYPE_FRAME_ROBOT_WORK_TIME_SET:
                        dataArea = FrameUtils.getDataArea(bytes);
                        String ok = HexStrUtils.bytesToHexString(dataArea);
                        if (timer!=null){
                            timer.cancel();
                        }
                        if (dialog!=null){
                            dialog.dismiss();
                        }
                        if (ok.equals("01")){
                            Toast.makeText(getContext(),getString(R.string.success_toast), Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getContext(),getString(R.string.fail_toast), Toast.LENGTH_SHORT).show();
                        }
                        break;
                    default:
                        break;
                }
            }
        }
    }

    @Override
    public void didGetHardwareInfo(GizWifiErrorCode result, GizWifiDevice device, ConcurrentHashMap<String, String> hardwareInfo) {

    }

    @Override
    public void didSetCustomInfo(GizWifiErrorCode result, GizWifiDevice device) {

    }

    @Override
    public void didUpdateNetStatus(GizWifiDevice device, GizWifiDeviceNetStatus netStatus) {

    }
    /**
     * 开始进度
     */

    private CountDownTimer timer = new CountDownTimer(10000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {
        }

        @Override
        public void onFinish() {
            Toast.makeText(getContext(),"time out ",Toast.LENGTH_SHORT).show();
            if (dialog!=null){
                dialog.dismiss();
            }
        }
    };
}
